/**
 * 获取文件
 */
const GetOneFile = (e: any, key?: string) => {
  let file = null
  // eslint-disable-next-line no-prototype-builtins
  if (File.prototype.isPrototypeOf(e)) {
    file = e
  } else if (e && e.target && e.target.files.length > 0) {
    file = e.target.files[0]
  }
  if (file) {
    return Promise.resolve(file)
  } else {
    return Promise.reject({ key, msg: '没有找到文件' }) // eslint-disable-line
  }
}

/**
 * 获取文件后缀
 */
const FileSuffix = async (e: any): Promise<string> => {
  const file = await GetOneFile(e)
  return Promise.resolve(file.name.split('.').pop())
}

/**
 * 获取本地图片
 */
const LocalImage = async (e: any, key = 'LocalImage') => {
  let file: File
  // eslint-disable-next-line no-prototype-builtins
  if (File.prototype.isPrototypeOf(e)) {
    file = e
  } else {
    file = await GetOneFile(e)
  }
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    //  读取操作完成时触发
    reader.onload = function () {
      resolve(this.result)
    }
    // 读取操作发生错误时触发
    reader.onerror = function () {
      reject({ key, msg: '读取失败' }) // eslint-disable-line
    }
    // 读取操作被中断时触发
    reader.onabort = function () {
      reject({ key, msg: '读取中断' }) // eslint-disable-line
    }
  })
}

/**
 * 是否有文件
 */
const ExistFile = (e: any) => {
  return e && e.target && e.target.files && e.target.files.length > 0
}

export { ExistFile, LocalImage, GetOneFile, FileSuffix }
